package com.xiangyun.xyojbackendjudgeservice.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xiangyun.xyojbackendcommon.common.ErrorCode;
import com.xiangyun.xyojbackendcommon.exception.BusinessException;
import com.xiangyun.xyojbackendjudgeservice.codesandbox.CodeSandBox;
import com.xiangyun.xyojbackendmodel.codesandbox.ExecuteRequest;
import com.xiangyun.xyojbackendmodel.codesandbox.ExecuteResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RemoteCodeSandBoxImpl implements CodeSandBox {

    //定义鉴权请求头
    private static final String AUTH_REQUEST_HEADER = "auth";
    //对应的秘钥
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExecuteResponse executeCode(ExecuteRequest executeRequest) {
        log.info("输出远程代码沙箱");
        String url = "http://192.168.40.138:8090/executeCode";
        //把对象转为JSON
        String json = JSONUtil.toJsonStr(executeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if(responseStr == null){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"executeCode remoteSandBox error message = " + responseStr);
        }
        //把JSON格式转为java对象
        return JSONUtil.toBean(responseStr,ExecuteResponse.class);
    }
}
